//
//  FXComposeViewController.swift
//  微博(Swift)
//
//  Created by V on 16/1/7.
//  Copyright © 2016年 V. All rights reserved.
//

import UIKit
import SnapKit

// 控件的间距
let FXComposeViewControllerMargin: CGFloat = 8

class FXComposeViewController: UIViewController {
    
    // toolBar 底部约束
    var toolBarBottonConstraint: Constraint?
    // toolBar 是否要执行动画，默认要
    var toolBarAnimation: Bool = true
    
    
    // MARK: - 懒加载控件
    private lazy var titleView: UILabel = {
        let titleView = UILabel()
        titleView.numberOfLines = 0
        titleView.textAlignment = .Center
        // 设置控制器的 title
        if let name = FXUserAccountViewModel.sharedViewModel.userAccount?.screen_name {
            let titleString = "发微博\n\(name)"
            // 将要显示的内容初始化为 可变的副文本
            let mutableAttributedStr = NSMutableAttributedString(string: titleString)
            // 求出 name 在整个字符串的位置与长度
            let range = (titleString as NSString).rangeOfString(name)
            // 给 name 添加属性
            mutableAttributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: range)
            mutableAttributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            // 空心文字效果
            // attr.addAttribute(NSStrokeColorAttributeName, value: UIColor.greenColor(), range: NSMakeRange(0, 3))
            // attr.addAttribute(NSStrokeWidthAttributeName, value: 1, range: NSMakeRange(0, 3))
            // 设置 titleView     的副文本
            titleView.attributedText = mutableAttributedStr
            // 注意：当控件显示不出来的时候，1. 是否添加到了View 上边 2. 是否设置好了frame
            // titleView.sizeToFit()
            // navigationItem.titleView = titleView
        }else{
            titleView.text = "发微博"
        }
        
        titleView.sizeToFit()
        return titleView
    }()
    //
    private lazy var textView: FXTextView = {
        let textView = FXTextView()
        textView.delegate = self
        textView.placeholder = "－你觉的这里大么？－大啊"
        textView.font = UIFont.systemFontOfSize(16)
        return textView
    }()
    // 发送按钮
    private lazy var rightButton: UIButton = {
        let button = UIButton()
        // 设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        // 设置不同状态的文字颜色
        button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        // 设置文字以及字体大小
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        button.setTitle("发送", forState: .Normal)
        
        button.frame.size = CGSize(width: 40, height: 30)
        return button
    }()
    // 文本编辑下边的工具栏
    private lazy var toolBar: FXComposeToolBar = {
        let toolBar = FXComposeToolBar(frame: CGRectZero)
        toolBar.buttonClickCloures = {[weak self](type) -> () in
            switch type {
            case .Picture:
                self!.selectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("＃")
            case .Emoticon:
                print("表情")
                self!.swtichKeyboard()
            case .Add:
                print("＋")
            }
        }
        return toolBar
    }()
    // FXComposePictureView
    private lazy var pictureView: FXComposePictureView = {
        let pictureView = FXComposePictureView()
        pictureView.addImageClickClourse = {[weak self] in
            self?.selectedPicture()
        }
        return pictureView
    }()
    // 懒加载表情键盘的View
    private lazy var emoticonKeyboard: FXEmoticonKeyboard = {
        let emoticonKeyboard = FXEmoticonKeyboard()
        emoticonKeyboard.frame.size = CGSize(width: SCREENW, height: 216)
        return emoticonKeyboard
    }()
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    
    
    // MARK: - 监听方法：
    @objc private func back(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    // 系统键盘 frame 改变的通知的监听方法
    @objc private func keyboardChangeFrame(notify: NSNotification){
        // notify 打印出来是一个字典，通过取到自己想要的值进行运用
        // print(notify)
        //
        if toolBarAnimation == false {
            return
        }
        
        if let endFrame = (notify.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
            // 单写这一句也可以实现 toolBar 的位置变更到系统键盘的上边。但是会有 闪一下的效果，所以要添加动画效果
            toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(self.view).offset(endFrame.origin.y - SCREENH)
            })
            // 取出动画执行的时间，目的：为了让键盘弹出的动画和 toolBar 的动画吻合
            let duration = (notify.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
            UIView.animateWithDuration(duration, animations: { () -> Void in
                self.toolBar.layoutIfNeeded()
            })
        }
    }
    // 表情button被选中的监听方法
    @objc private func emoticonDidSelected(notify: NSNotification) {
        let emoticon = notify.object as! FXEmoticon
        if emoticon.type! == "0" { // 是图片表情
            // print("图片表情")
            // 把表情添加到TextView上
            // 1. 通过图片初始化一个文字附件
            let image = UIImage(named: emoticon.fullPath, inBundle: FXEmoticonTools.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
            let attachment = NSTextAttachment()
            attachment.image = image
            // 2. 通过文字附件初始化成一个 NSAttributedString 
            let attributeString = NSAttributedString(attachment: attachment)
            // 3. 给 textView 设置一个 attributeText
            let originalAttr = NSMutableAttributedString(attributedString: textView.attributedText)
            originalAttr.appendAttributedString(attributeString)
            textView.attributedText = originalAttr
        }else {
            print("emoji")
        }
    }
    
    
    
    
    // 点击 toolBar 的图片按钮弹出选择图片的控制器
    @objc private func selectedPicture(){
        // UIImagePickerController 是系统提供的控制器
        let vc = UIImagePickerController()
        vc.delegate = self
        //        vc.allowsEditing = true
        vc.sourceType = .PhotoLibrary
        presentViewController(vc, animated: true, completion: nil)
    }
    // 点击 toolBar 的表情按钮
    @objc private func swtichKeyboard(){
        // 1. 如果系统键盘存在：1》取消第一响应 2》弹出表情键盘   2. 如果系统键盘不存在： 1》直接弹出表情键盘
        // 不管系统键盘是否弹出来了都应该取消第一响应者，为需要弹出的键盘做准备
        toolBarAnimation = false
        textView.resignFirstResponder()
        
        if textView.inputView == nil{
            // 系统键盘没有弹出来的时候点击了表情按钮。表情键盘只是一个 View。不是系统键盘
            textView.inputView = emoticonKeyboard
            toolBar.isSystemKeyboard = false
        }else{
            // 键盘已经弹出来的时候点击了表情按钮
            textView.inputView = nil
            toolBar.isSystemKeyboard = true
        }
        toolBarAnimation = true
        textView.becomeFirstResponder()
    }
    
}





// 界面设置
extension FXComposeViewController {
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "back")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
        // 设置发送微博标题
        navigationItem.titleView = titleView
        // 添加控件
        view.addSubview(textView)
        view.addSubview(toolBar)
        view.addSubview(pictureView)
        // 约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        // toolBar 的约束
        toolBar.snp_makeConstraints { (make) -> Void in
            toolBarBottonConstraint = make.bottom.equalTo(self.view).constraint
            make.height.equalTo(44)
            make.leading.equalTo(self.view)
            make.trailing.equalTo(self.view)
        }
        // picView 的约束
        pictureView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(textView).offset(FXComposeViewControllerMargin)
            make.width.equalTo(textView).offset(-2 * FXComposeViewControllerMargin)
            make.top.equalTo(textView).offset(200)
            make.height.equalTo(pictureView.snp_width)
        }
        
        // 键盘弹出通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDidSelected:", name: FXEmoticonDidSelectedNotification, object: nil)
    }
}




// MARK: - UIImagePickerController 的代理方法
extension FXComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    // 选择图片结束后调用的方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        pictureView.addImage(image)
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}




// MARK: - 编辑框的代理方法
extension FXComposeViewController: UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}







